import * as ECharts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'

const HANDLER = '_vue_resize_handler'

// Vue 3 指令需要导出一个对象，使用 mounted 和 unmounted 钩子替代 bind 和 unbind
export const chartResize = {
  mounted(el, binding) {
    el[HANDLER] = binding.value
      ? binding.value
      : () => {
          let chart = ECharts.getInstanceByDom(el)

          if (!chart) {
            return
          }
          chart.resize()
        }
    // 监听绑定的div大小变化，更新 echarts 大小
    elementResizeDetectorMaker().listenTo(el, el[HANDLER])
  },

  unmounted(el) {
    elementResizeDetectorMaker().removeListener(el, el[HANDLER])
    delete el[HANDLER]
  }
}
